<template>
	<div ref="questionStatus" style="width:100%;height:400px;"></div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import * as echarts from 'echarts';

let props = defineProps({
	info: {
		type: Object,
		default: {}
	}
})

let questionStatus = ref(null);

let chart = ''

let getechartss = () => {

	let option = {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross'
			},
		},

		legend: {
			data: [$t('home.salesVolume'), $t('home.sales')]
		},

		grid: {
			left: 10,
			right: 10,
			bottom: 20,
			top: 30,
			containLabel: true
		},

		// 下方X轴
		xAxis: {
			type: 'category',
			boundaryGap: true,
			data: props.info.date
		},

		// 单 左侧Y轴
		// yAxis: {
		// 	type: 'value'
		// },

		// 双 Y轴
		yAxis: [
			{
				type: 'value',
				name: $t('home.sales'),
				axisLine: {
					show: true,
					lineStyle: {
						color: '#bbb'
					}
				},
			},
			{
				type: 'value',
				name: $t('home.salesVolume'),
				axisLine: {
					show: true,
					lineStyle: {
						color: '#bbb'
					}
				},
			}
		],

		series: [
			{
				name: $t('home.sales'),
				type: 'line',
				data: props.info.revenue,
				smooth: true,
				lineStyle: {
					color: '#E02222',
					width: 4
				},
				itemStyle: {
					color: '#E02222',
				}
			},
			{
				name: $t('home.salesVolume'),
				type: 'bar',
				yAxisIndex: 1,
				data: props.info.sales,
				smooth: true,
				barWidth: '26%',
				itemStyle: {
					color: '#8A8A8A'
				}
			}
		],
	};

	chart = echarts.init(questionStatus.value)

	chart.setOption(option)

	window.addEventListener('resize', function () {
		chart.resize();
	})

	// 自适应容器大小 start
	let chartsPromise = new Promise((resolve) => {
		chart.on("finished", () => {
			// console.log("finished函数被触发");
			resolve(); // 把执行结果抛出去
		})
	})

	chartsPromise.then(() => {
		objResizeObserver.observe(questionStatus.value)
	})

	let objResizeObserver = new ResizeObserver(function (entries) {
		// console.log("观察者函数被执行");
		throttledFun();
	});

	let throttle = (fn, wait) => {
		let timer = null;
		return function () {
			let context = this;
			let args = arguments;
			if (!timer) {
				// 当延迟时间结束后，执行函数
				timer = setTimeout(() => {
					timer = null;
					fn.apply(context, args);
				}, wait);
			}
		}
	}

	let throttledFun = throttle(function () {
		console.log("节流函数被触发");
		chart.resize(); // 调整echarts尺寸
	}, 1000);
	// 自适应容器大小 end

}

// 触发图表加载
let trigger = () => {
	if (chart != '') {
		chart.dispose(); // 销毁图表
	}
	setTimeout(() => {
		getechartss() // 生成新的图表
	}, 100)
}

// 抛出事件，让父组件允许触发
defineExpose({
	trigger
});

// 加载完页面触发
// onMounted(() => {
// 	getechartss()
// })


</script>
